<template>
  <div class="page-container">
    <!-- 读取配置中 -->
    <template v-if="!userStore.epServiceTypes">
      <a-spin dot />
    </template>
    <template v-else>
      <!-- 暂未配置 -->
      <template v-if="userStore.epServiceTypes?.length == 0">
        <div class="no-config">
          <SvgIcon name="no-config" style="width: 100%; height: 100%" />
          <p>当前商户未配置服务类型，请选择本商户支持服务类型</p>
        </div>
      </template>
      <template v-else>
        <a-tabs v-model:active-key="activeTabsKey" @change="tabsChangeFn">
          <!-- 配置了短长租业务才显示对应的长短租选项 -->
          <a-tab-pane key="1" title="自驾短租" v-if="userStore.epServiceTypes.includes(1)" />
          <a-tab-pane key="2" title="自驾长租" v-if="userStore.epServiceTypes.includes(2)" />
        </a-tabs>
        <div class="price-config-wrapper">
          <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
          <table-index :table="table" :rowKey="`id`" @loadData="loadData">
            <!-- 模板名称 -->
            <template #templateName="{ record }">
              {{ record.templateName }}
              <!-- 系统模板 -->
              <a-tooltip
                content="全局车型基础价，车型价格未配置，自营小程序此车型对客户隐藏，商户后台代客下单此车型费用不回填"
                v-if="record.templateType == 1"
              >
                <!-- <icon-info-circle-fill style="font-size: 16px; color: #165dff; vertical-align: middle" /> -->
                <icon-exclamation-circle style="font-size: 16px; color: #165dff; vertical-align: middle" />
              </a-tooltip>
            </template>
            <template #siteNum="{ record }">
              <div class="site-num-wrapper">
                <span class="site-num-val">{{ record.templateType == 1 ? '全部' : record.siteNum }}</span>
                <a-button type="outline" size="mini" class="view-btn" @click="viewSiteListFn(record)">查看</a-button>
              </div>
            </template>
            <template #model-status="{ record }">
              <status-tag :value="record.status" :label="record.statusStr" />
              <!-- <div class="flex items-center status-wrapper">
                <span :class="[record.status == '0' ? 'close' : 'open', 'status-icon']"></span>
                <span>{{ record.statusStr }}</span>
              </div> -->
            </template>
          </table-index>
        </div>
      </template>
    </template>
    <!-- 模板门店弹窗 -->
    <template-site-modal ref="templateSiteModalRef" />
  </div>
</template>

<script setup name="CommonPriceList">
  import { ref, reactive, computed, watch } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { getTemplateList, setTemplateEnabled, getTemplateSiteList } from '@/api/business/common.js'
  import { usePageDict } from '@/hooks/useDict'
  import { Modal, Message } from '@arco-design/web-vue'
  import templateSiteModal from '../components/template-site-modal.vue'
  import useNavigate from '@/hooks/useNavigate'
  // 读取商户配置开始
  import useUserStore from '@/store/modules/user'

  const { navigateTo } = useNavigate()
  const userStore = useUserStore()
  // 初始化获取当前商户配置下默认长短租选中
  userStore.setEpDetail(() => {
    activeTabsKey.value = userStore.epServiceTypes[0]
    // 初始化查询
    queryParam.templateSort = activeTabsKey.value.toString()
    loadData()
  })
  // 读取商户配置结束
  // tabs 相关 开始
  const activeTabsKey = ref('')
  // 切换 tabs
  const tabsChangeFn = (val) => {
    activeTabsKey.value = val
    queryParam.templateSort = val
    // 清空 查询条件 开始
    for (var k in queryParam) {
      if (k != 'templateSort') {
        queryParam[k] = undefined
      }
    }
    // 清空 查询条件 结束
    loadData(1)
  }
  // tabs 相关 结束
  // 页面初始化 开始
  watch(
    () => userStore.epServiceTypes,
    (newVal, oldVal = []) => {
      if (newVal && newVal.toString() != oldVal.toString()) {
        if (!newVal.find((item) => item == activeTabsKey.value)) {
          const initServiceType = newVal[0]
          activeTabsKey.value = initServiceType.toString()
          queryParam.templateSort = activeTabsKey.value
          loadData(1)
        }
      }
    }
  )
  // 页面初始化 结束
  // 接口参数（不包含page信息）
  const queryParam = reactive({})
  // 列表接口调用
  const loadData = (page) => {
    const fn = useFetchTableDataApi(table, queryParam, getTemplateList)
    fn(page).then((result) => {
      console.log(result)
    })
  }

  // 查看门店列表弹窗
  const templateSiteModalRef = ref()
  const viewSiteListFn = (record) => {
    templateSiteModalRef.value.open(record, getTemplateSiteList)
  }

  // 添加模板
  const addTemplateFn = () => {
    const templateSort = queryParam.templateSort
    navigateTo('/common-price/create?templateSort=' + templateSort, `新增${templateSort == 1 ? '短租' : '长租'}通用费用`)
  }
  // 编辑模板
  const editTemplateFn = (record) => {
    const templateSort = queryParam.templateSort
    navigateTo(
      `/common-price/edit/${record.id}?templateType=${record.templateType}&templateSort=${templateSort}`,
      `${record.templateName}-编辑`
    )
  }
  // 模板启用停用
  const toggleStatusFn = (record, operateName) => {
    new Promise((resolve) => {
      if (operateName == '启用') {
        resolve()
      } else {
        // 停用需要加二次确认
        Modal.confirm({
          title: '提示',
          simple: true,
          cancelText: '取消',
          okText: '确认',
          content: `请确认，是否停用？`,
          onOk: () => {
            resolve()
          },
        })
      }
    }).then(() => {
      const param = {
        id: record.id,
        status: operateName == '启用' ? 1 : 0,
      }
      setTemplateEnabled(param).then(() => {
        Message.success(`${operateName}成功`)
        // 手动更改状态
        loadData()
      })
    })
  }
  // 查询条件
  const dict = usePageDict('tenantCostDict')
  const searchList = computed(() => {
    return [
      { label: '通用费用名称', prop: 'templateNameLike', type: 'a-input' },
      {
        label: '应用门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_lease_list',
        },
      },
      {
        label: '模板状态',
        prop: 'status',
        type: 'a-select',
        options: dict.statusMap,
      },
    ]
  })

  // table 配置
  const table = useTable({
    columns: [
      { title: '通用费用名称', dataIndex: 'templateName' },
      { title: '应用门店数', dataIndex: 'siteNum', slotName: 'siteNum' },
      { title: '通用费用状态', dataIndex: 'statusStr', slotName: 'model-status' },
    ],
    operates: [
      {
        label: '编辑',
        permission: 'svms:business:price:common.edit',
        method: (record) => {
          editTemplateFn(record)
        },
      },
      {
        label: '启用',
        permission: 'svms:business:price:common.enable',
        // 停用状态显示启用按钮
        show: (record) => record.status == 0 && record.templateType != 1,
        method: (record) => {
          toggleStatusFn(record, '启用')
        },
      },
      {
        label: '停用',
        permission: 'svms:business:price:common.disable',
        // 停用状态显示启用按钮
        show: (record) => record.status == 1 && record.templateType != 1,
        method: (record) => {
          toggleStatusFn(record, '停用')
        },
      },
    ],
    buttons: [
      {
        type: 'primary',
        icon: 'plus',
        label: '新增',
        permission: 'svms:business:price:common.add',
        method: () => {
          addTemplateFn()
        },
      },
    ],
  })
</script>

<style lang="less" scoped>
  .status-wrapper {
    height: 28px;
    .status-icon {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
      &.open {
        background: #00b42a;
      }
      &.close {
        background: #ea0000;
      }
    }
  }
  .no-config {
    width: 235px;
    height: 154px;
    padding-bottom: 40px;
    position: absolute;
    left: 50%;
    top: 20vh;
    margin-left: -117px;
    p {
      padding-top: 20px;
      text-align: center;
      font-size: 16px;
      color: #cad0dd;
    }
  }

  .site-num-wrapper {
    font-size: 14px;
    .site-num-val {
      vertical-align: middle;
      line-height: 20px;
    }
    .view-btn {
      border-radius: 2px;
      opacity: 1;
      border: 1px solid #1890ff;
      color: #1890ff;
      margin-left: 6px;
      height: 18px;
      line-height: 18px;
      padding: 0 8px;
      font-size: 12px;
      vertical-align: middle;
    }
  }
</style>
